package com.example.apisix.plugin;

import lombok.extern.slf4j.Slf4j;
import org.apache.apisix.plugin.runner.HttpRequest;
import org.apache.apisix.plugin.runner.HttpResponse;
import org.apache.apisix.plugin.runner.filter.PluginFilter;
import org.apache.apisix.plugin.runner.filter.PluginFilterChain;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ErrorPlugin implements PluginFilter {
    @Override
    public String name() {
        return "ErrorPlugin";
    }

    /**
     * 插件处理异常，分两种情况：1.返回状态码是500。2.抛异常
     * @param request 请求对象
     * @param response 响应对象
     * @param chain PluginFilterChain
     */
    @Override
    public void filter(HttpRequest request, HttpResponse response, PluginFilterChain chain) {
        String body = request.getBody();
        log.info("body:{}", body);
        if (body.contains("error")) {
            response.setStatusCode(500);
            response.setBody("error message");
            return;
        }
        throw new RuntimeException("exception");
    }

    @Override
    public Boolean requiredBody() {
        return true;
    }
}
